perm filename OC3.WEB[MF,ALS]2 blob sn#769348 filedate 1984-09-16 generic text, type C, neo UTF8
COMMENT ⊗   VALID 00015 PAGES
C REC  PAGE   DESCRIPTION
C00001 00001
C00003 00002	% This program is based on GFtype and in part contains material extracted from
C00006 00003	@* Introduction.
C00015 00004	@* Optional modes of output.
C00024 00005	@* The character set.
C00032 00006	@* Generic font file format.
C00057 00007	@* Input and Output for binary files.
C00067 00008	@* Reading the gf information.
C00076 00009	@* Translating the input commands.  This section will be largely concerned with
C00083 00010	@* Processing and writing out the raster information.
C00091 00011	@* Reading the postamble.
C00110 00012	@* OC File Format.
C00128 00013	@* The main program.
C00136 00014	@* System-dependent changes.
C00137 00015	@* Index.
C00138 ENDMK
C⊗;
% This program is based on GFtype and in part contains material extracted from
% program GFtoPXL which, in turn, was extracted from GFtoAMF.
% Version 0 was implemented in June 1984.

% Here is TeX material that gets inserted after \input webmac
\def\hang{\hangindent 3em\noindent\ignorespaces}
\def\textindent#1{\hangindent2.5em\noindent\hbox to2.5em{\hss#1 }\ignorespaces}
\font\ninerm=amr9
\let\mc=\ninerm % medium caps for names like PASCAL
\font\tenss=amss10 % for `The METAFONTbook'
\def\PASCAL{{\mc PASCAL}}
\def\ph{{\mc PASCAL-H}}
\font\logo=manfnt % font used for the METAFONT logo
\def\MF{{\logo META}\-{\logo FONT}}
\def\<#1>{$\langle#1\rangle$}
\def\section{\mathhexbox278}
\let\swap=\leftrightarrow
\def\round{\mathop{\rm round}\nolimits}

\def\today{\ifcase\month\or
  January\or February\or March\or April\or May\or June\or
  July\or August\or September\or October\or November\or December\fi
  \space\number\day, \number\year}

\def\(#1){} % this is used to make section names sort themselves better
\def\9#1{} % this is used for sort keys in the index via @@:sort key}{entry@@>

\def\title{GFDOVER}
\def\topofcontents{\null
	\def\titlepage{F} % include headline on the contents page
	\def\rheader{\mainfont\hfil \contentspagenumber}
	\vfill
	\centerline{\titlefont The {\ttitlefont GFDOVER} processor}
	\vskip 15pt
	\centerline{(Version 0.1, September 1984)}
	\vfill}
\def\botofcontents{\vfill
	\centerline{\hsize 5in\baselineskip9pt
		\vbox{\ninerm\noindent
		The preparation of this report
		was supported in part by the National Science
		Foundation under grants IST-8201926 and MCS-8300984,
		and by the System Development Foundation. `\TeX' is a
		trademark of the American Mathematical Society.}}}
\pageno=\contentspagenumber \advance\pageno by 1
@* Introduction.
The \.{GFDOVER} utility program reads binary generic-font (``\.{GF}'')
files that are produced by font compilers such as \MF, and generates
two output files as required by the \.{DOVER} printer.  One of these files
is an \.{OC} formatted file that differ from a \.{PXL} file in that the
raster is rotated 90 degrees, that is, scanned from bottom-to-top,
left-to-right to conform with the Dover's scan, and also differs in detail
as to the overall format.  The second file is a \.{WD} formatted file that
contains the width information that \.{DOVER} requires.

The |banner| string defined here should be changed whenever \.{GFDOVER}
gets modified.

@d banner=='This is GFDOVER, Version 0.1' {printed when the program starts}
@d resolution==384.0  {pixels per inch, as used in gf files}
@d xresolution==5.313408  {pixels per point}
@d yresolution==5.313408  {as used in |oc| and |wd| files}
@d ppi==72.27  { Points per inch}

@ This program is written in standard \PASCAL, except where it is
necessary to use extensions; for example, one extension is to use a
default |case| as in \.{TANGLE}, \.{WEAVE}, etc.  All places where
nonstandard constructions are used have been listed in the index under
``system dependencies.''
@!@↑system dependencies@>

@d othercases == others: {default for cases not listed explicitly}
@d endcases == @+end {follows the default case in an extended |case| statement}
@f othercases == else
@f endcases == end

@ The binary input comes from |gf_file|, and the output font is written
on |oc_file|.  Status reporting and error messages appear
on \PASCAL's standard |output| file. The term |print| is used instead of
|write| when this program writes on |output|, so that all such output
could easily be redirected if desired.

@d print(#)==write(#)
@d print_ln(#)==write_ln(#)
@d print_nl==write_ln

@p program GF_to_OC(@!gf_file,@!oc_file,@!wd_file,@!output);
label @<Labels in the outer block@>@/
const @<Constants in the outer block@>@/
type @<Types in the outer block@>@/
var @<Globals in the outer block@>@/
procedure initialize; {this procedure gets things started properly}
	var i:integer; {loop index for initializations}
	begin print_ln(banner);@/
	@<Set initial values@>@/
	end;

@ If the program has to stop prematurely, it goes to the
`|final_end|'.

@d final_end=9999 {label for the end of it all}

@<Labels...@>=final_end;

@ The following parameters can be changed at compile time to extend or
reduce |GF_to_OC|'s capacity. The use of 127 as the |max_glyph_no| is
required by \.{DOVER}, although we may want to arrange to allow this
number to be increased to 255.

@<Constants...@>=
@!line_length=79; {bracketed lines of output will be at most this long}
@!terminal_line_length=150; {maximum number of characters input in a single
	line of input from the terminal}
@!max_glyph_no=127; {maximum glyph number in font}
@!top_pixel=400; {boundary of pixel image of glyph}
@!bot_pixel=-150;
@!left_pixel=-150;
@!right_pixel=400;
@!max_p_c=50;

@ Here are some macros for common programming idioms.

@d incr(#) == #←#+1 {increase a variable by unity}
@d decr(#) == #←#-1 {decrease a variable by unity}
@d negate(#) == #←-# {change the sign of a variable}
@d do_nothing == {empty statement}

@d min_y_allowed == bot_pixel
@d max_y_allowed == top_pixel
@d min_x_allowed == left_pixel
@d max_x_allowed == right_pixel

@ If the \.{GF} file is badly malformed, the whole process must be aborted;
\.{GFDOVER} will give up, after issuing an error message about the symptoms
that were noticed.

Such errors might be discovered inside of subroutines inside of subroutines,
so a procedure called |jump_out| has been introduced. This procedure, which
simply transfers control to the label |final_end| at the end of the program,
contains the only non-local |goto| statement in \.{GFDOVER}.
@↑system dependencies@>

@d abort(#)==begin print(' ',#); jump_out;
		end
@d bad_gf(#)==abort('Bad GF file: ',#,'!')
@.Bad GF file@>

@p procedure jump_out;
begin goto final_end;
end;

@ We copy the following routine from \MF.

@d unity == @'200000 {$2↑{16}$, represents 1.00000}


@ We will need the following procedures:

@p procedure print_scaled(@!s:integer); {prints scaled real, rounded to five
	digits}
var @!delta:integer; {amount of allowable inaccuracy}
begin if s<0 then
	begin print('-'); negate(s); {print the sign, if negative}
	end;
print(s div unity:1); {print the integer part}
s←10*(s mod unity)+5;
if s≠5 then
	begin delta←10; print('.');
	repeat if delta>unity then
		s←s+@'100000-(delta div 2); {round the final digit}
	print(chr(ord('0')+(s div unity))); s←10*(s mod unity); delta←delta*10;
	until s≤delta;
	end;
end;
@* Optional modes of output.
The following is left in the program to simplify the addition of some
input and output routines should these be needed later.

The |input_ln| routine waits for the user to type a line at his or her
terminal; then it puts ASCII-code equivalents for the characters on that line
into the |buffer| array. The |term_in| file is used for terminal input,
and |term_out| for terminal output.
@↑system dependencies@>

@<Glob...@>=
@!buffer:array[0..terminal_line_length] of ASCII_code;
@!term_in:text_file; {the terminal, considered as an input file}
@!term_out:text_file; {the terminal, considered as an output file}

@ Humdrum.
@p function lower_casify(@!c:ASCII_code):ASCII_code;
begin
if (c≥"A") and (c≤"Z") then lower_casify←c+"a"-"A"
else lower_casify←c;
end;
@* The character set.
Like all programs written with the  \.{WEB} system, \.{GFDOVER} can be
used with any character set. But it uses ASCII code internally, because
the programming for portable input-output is easier when a fixed internal
code is used.

The next few sections of \.{GFDOVER} have therefore been copied from the
analogous ones in the \.{WEB} system routines. They have been considerably
simplified, since \.{GFDOVER} need not deal with the controversial
ASCII codes less than @'40. If such codes appear in the \.{GF} file,
they will be printed as question marks.

@<Types...@>=
@!ASCII_code=" ".."~"; {a subrange of the integers}

@ The original \PASCAL\ compiler was designed in the late 60s, when six-bit
character sets were common, so it did not make provision for lower case
letters. Nowadays, of course, we need to deal with both upper and lower case
alphabets in a convenient way, especially in a program like \.{GFDOVER}.
So we shall assume that the \PASCAL\ system being used for \.{GFDOVER}
has a character set containing at least the standard visible characters
of ASCII code (|"!"| through |"~"|).

Some \PASCAL\ compilers use the original name |char| for the data type
associated with the characters in text files, while other \PASCAL s
consider |char| to be a 64-element subrange of a larger data type that has
some other name.  In order to accommodate this difference, we shall use
the name |text_char| to stand for the data type of the characters in the
output file.  We shall also assume that |text_char| consists of
the elements |chr(first_text_char)| through |chr(last_text_char)|,
inclusive. The following definitions should be adjusted if necessary.
@↑system dependencies@>

@d text_char == char {the data type of characters in text files}
@d first_text_char=0 {ordinal number of the smallest element of |text_char|}
@d last_text_char=127 {ordinal number of the largest element of |text_char|}

@<Types...@>=
@!text_file=packed file of text_char;

@ The \.{GFDOVER} processor converts between ASCII code and
the user's external character set by means of arrays |xord| and |xchr|
that are analogous to \PASCAL's |ord| and |chr| functions.

@<Globals...@>=
@!xord: array [text_char] of ASCII_code;
	{specifies conversion of input characters}
@!xchr: array [0..255] of text_char;
	{specifies conversion of output characters}

@ Under our assumption that the visible characters of standard ASCII are
all present, the following assignment statements initialize the
|xchr| array properly, without needing any system-dependent changes.

@<Set init...@>=
for i←0 to @'37 do xchr[i]←'?';
xchr[@'40]←' ';
xchr[@'41]←'!';
xchr[@'42]←'"';
xchr[@'43]←'#';
xchr[@'44]←'$';
xchr[@'45]←'%';
xchr[@'46]←'&';
xchr[@'47]←'''';@/
xchr[@'50]←'(';
xchr[@'51]←')';
xchr[@'52]←'*';
xchr[@'53]←'+';
xchr[@'54]←',';
xchr[@'55]←'-';
xchr[@'56]←'.';
xchr[@'57]←'/';@/
xchr[@'60]←'0';
xchr[@'61]←'1';
xchr[@'62]←'2';
xchr[@'63]←'3';
xchr[@'64]←'4';
xchr[@'65]←'5';
xchr[@'66]←'6';
xchr[@'67]←'7';@/
xchr[@'70]←'8';
xchr[@'71]←'9';
xchr[@'72]←':';
xchr[@'73]←';';
xchr[@'74]←'<';
xchr[@'75]←'=';
xchr[@'76]←'>';
xchr[@'77]←'?';@/
xchr[@'100]←'@@';
xchr[@'101]←'A';
xchr[@'102]←'B';
xchr[@'103]←'C';
xchr[@'104]←'D';
xchr[@'105]←'E';
xchr[@'106]←'F';
xchr[@'107]←'G';@/
xchr[@'110]←'H';
xchr[@'111]←'I';
xchr[@'112]←'J';
xchr[@'113]←'K';
xchr[@'114]←'L';
xchr[@'115]←'M';
xchr[@'116]←'N';
xchr[@'117]←'O';@/
xchr[@'120]←'P';
xchr[@'121]←'Q';
xchr[@'122]←'R';
xchr[@'123]←'S';
xchr[@'124]←'T';
xchr[@'125]←'U';
xchr[@'126]←'V';
xchr[@'127]←'W';@/
xchr[@'130]←'X';
xchr[@'131]←'Y';
xchr[@'132]←'Z';
xchr[@'133]←'[';
xchr[@'134]←'\';
xchr[@'135]←']';
xchr[@'136]←'↑';
xchr[@'137]←'_';@/
xchr[@'140]←'`';
xchr[@'141]←'a';
xchr[@'142]←'b';
xchr[@'143]←'c';
xchr[@'144]←'d';
xchr[@'145]←'e';
xchr[@'146]←'f';
xchr[@'147]←'g';@/
xchr[@'150]←'h';
xchr[@'151]←'i';
xchr[@'152]←'j';
xchr[@'153]←'k';
xchr[@'154]←'l';
xchr[@'155]←'m';
xchr[@'156]←'n';
xchr[@'157]←'o';@/
xchr[@'160]←'p';
xchr[@'161]←'q';
xchr[@'162]←'r';
xchr[@'163]←'s';
xchr[@'164]←'t';
xchr[@'165]←'u';
xchr[@'166]←'v';
xchr[@'167]←'w';@/
xchr[@'170]←'x';
xchr[@'171]←'y';
xchr[@'172]←'z';
xchr[@'173]←'{';
xchr[@'174]←'|';
xchr[@'175]←'}';
xchr[@'176]←'~';
for i←@'177 to 255 do xchr[i]←'?';

@ The following system-independent code makes the |xord| array contain a
suitable inverse to the information in |xchr|.

@<Set init...@>=
for i←first_text_char to last_text_char do xord[chr(i)]←@'40;
for i←" " to "~" do xord[xchr[i]]←i;
@* Generic font file format.
The most important output produced by a production run of \MF\ is the
``generic font'' (\.{GF}) file that specifies the bit patterns of the
characters that have been drawn. The term {\sl generic\/} indicates that
this file format doesn't match the conventions of any name-brand manufacturer;
but it is easy to convert \.{GF} files to the special format required by
almost all digital phototypesetting equipment. There's a strong analogy
between the \.{DVI} files written by \TeX\ and the \.{GF} files written
by \MF; and, in fact, the file formats have a lot in common.

A \.{GF} file is a stream of 8-bit bytes that may be
regarded as a series of commands in a machine-like language. The first
byte of each command is the operation code, and this code is followed by
zero or more bytes that provide parameters to the command. The parameters
themselves may consist of several consecutive bytes; for example, the
`|boc|' (beginning of character) command has seven parameters, each of
which is four bytes long. Parameters are usually regarded as nonnegative
integers; but four-byte-long parameters can be either positive or
negative, hence they range in value from $-2↑{31}$ to $2↑{31}-1$.
As in \.{TFM} files, numbers that occupy
more than one byte position appear in BigEndian order,
and negative numbers appear in two's complement notation.

A \.{GF} file consists of a ``preamble,'' followed by a sequence of one or
more ``characters,'' followed by a ``postamble.'' The preamble is simply a
|pre| command, with its parameters that introduce the file; this must come
first.  Each ``character'' consists of a |boc| command, followed by any
number of other commands that specify the ``black'' pixels of a character,
followed by an |eoc| command. The characters appear in the order that \MF\
generated them. If we ignore no-op commands (which are allowed between any
two commands in the file), each |eoc| command is immediately followed by a
|boc| command, or by a |post| command; in the latter case, there are no
more characters in the file, and the remaining bytes form the postamble.
Further details about the postamble will be explained later.

Some parameters in \.{GF} commands are ``pointers.'' These are four-byte
quantities that give the location number of some other byte in the file;
the first byte is number~0, then comes number~1, and so on.

@ The \.{GF} format is intended to be both compact and easily interpreted
by a machine. Compactness is achieved by making most of the information
relative instead of absolute. When a \.{GF}-reading program reads the
commands for a character, it keeps track of several quantities: (a)~the current
row number,~|y|; (b)~the current column number,~|x|; and (c)~the current
starting-column number,~|z|. These are 32-bit signed integers, although
most actual font formats produced from \.{GF} files will need to curtail
this vast range because of practical limitations. (\MF\ output will never
allow $\vert x\vert$, $\vert y\vert$, or $\vert z\vert$ to exceed 4095,
but the \.{GF} format tries to be more general.)

How do \.{GF}'s row and column numbers correspond to the conventions
of \TeX\ and \MF? Well, the ``reference point'' of a character, in \TeX's
view, is considered to be at the lower left corner of the pixel in row~0
and column~0. This point is the intersection of the baseline with the left
edge of the type; it corresponds to location $(0,0)$ in \MF\ programs.
Thus the pixel in row~0 and column~0 is \MF's unit square, comprising the
region of the plane whose coordinates both lie between 0 and~1. Negative
values of~|y| correspond to rows of pixels {\sl below\/} the baseline.

Besides |x|, |y|, and |z|, there's also a fourth aspect of the current
state, namely the @!|paint_switch|, which is always either \\{black} or
\\{white}. Each \\{paint} command advances |x| by a specified amount~|d|,
and blackens the intervening pixels if |paint_switch=black|; then
the |paint_switch| changes its state. \.{GF}'s commands are designed so
that |x| will never decrease within a row, and |y| will never increase
within a character; hence there is no way to whiten a pixel that has
been blackened. Rather than using the |paint_switch| parameter directly,
as is done in \.{GFTYPE}, we will find it convenient to store values in a
|paint_val| array, as will be explained in more detail below.

@ Here is a list of all the commands that may appear in a \.{GF} file. Each
command is specified by its symbolic name (e.g., |boc|), its opcode byte
(e.g., 67), and its parameters (if any). The parameters are followed
by a bracketed number telling how many bytes they occupy; for example,
`|d[2]|' means that parameter |d| is two bytes long.

\yskip\hang|paint_0| 0. This is a \\{paint} command with |d=0|; it does
nothing but change the |paint_switch| from \\{black} to \\{white} or vice~versa.

\yskip\hang\\{paint\_1} through \\{paint\_63} (opcodes 1 to 63).
These are \\{paint} commands with |d=1| to~63, defined as follows: If
|paint_switch=black|, blacken |d|~pixels of the current row~|y|,
in columns |x| through |x+d-1| inclusive. Then, in any case,
complement the |paint_switch| and advance |x| by~|d|.

\yskip\hang|paint1| 64 |d[1]|. This is a \\{paint} command with a specified
value of~|d|; \MF\ uses it to paint when |64≤d<256|.

\yskip\hang|@!paint2| 65 |d[2]|. Same as |paint1|, but |d|~can be as high
as~65535.

\yskip\hang|@!paint3| 66 |d[3]|. Same as |paint1|, but |d|~can be as high
as $2↑{24}-1$. \MF\ never needs this command, and it is hard to imagine
anybody making practical use of it; surely a more compact encoding will be
desirable when characters can be this large. But the command is there,
anyway, just in case.

\yskip\hang|boc| 67 |c[4]| |p[4]| |min_x[4]| |max_x[4]| |min_y[4]|
|max_y[4]| |z[4]|. Beginning of a character:  Here |c| is the character
code, and |p| points to the previous |boc| command (if any) for characters
having this code number modulo 256.  (The pointer |p| is |-1| if there was
no prior character with an equivalent code.) All $x$-coordinates of black
pixels in the character that follows will be |≥min_x| and |≤max_x|; all
$y$-coordinates of black pixels will be |≥min_y| and |≤max_y|. Finally,
|z|~is the leftmost potentially black column in row |max_y|; it satisfies
|min_x≤z≤max_x|. When a \.{GF}-reading program sees a |boc|, it can use
|min_x|, |max_x|, |min_y|, and |max_y| to initialize the bounds of an
array. Then it sets |y←max_y|, |paint_switch←black|, and initializes its
|x| and |z| registers to the stated value of~|z|.

\yskip\hang|eoc| 68. End of character: All pixels blackened so far
constitute the pattern for this character. In particular, a completely
blank character might have |eoc| immediately following |boc|.

\yskip\hang|skip1| 69 |m[1]|. Decrease |y| by |m+1|, set |x←z|, and set
|paint_switch←black|. This is a way to produce |m| all-white rows.

\yskip\hang|@!skip2| 70 |m[2]|. Same as |skip1|, but |m| can be as large
as 65535.

\yskip\hang|@!skip3| 71 |m[3]|. Same as |skip1|, but |m| can be as large
as $2↑{24}-1$. \MF\ obviously never needs this command.

\yskip\hang|new_row| 72 |u[4]|. Decrease |y| by 1 and set |z←z+u|; then set
|x←z| and |paint_switch←black|. (It's a general way to finish one row
and begin another.)

\yskip\hang|@!left_z_83| through |@!left_z_1| (opcodes 73 to 155). Same as
|new_row|, with |u=-83| through |-1|, respectively.

\yskip\hang|right_z_0| 156. Same as |skip1| with |m=0| or |new_row| with
|u=0|.

\yskip\hang|@!right_z_1| through |@!right_z_83| (opcodes 157 to 239). Same as
|new_row|, with |u=+1| through |+83|, respectively. \MF\ generates a
|new_row| command only when $\vert u\vert>83$.

\yskip\hang|@!nop| 240. No operation, do nothing. Any number of |nop|'s
may occur between \.{GF} commands, but a |nop| cannot be inserted between
a command and its parameters or between two parameters.

\yskip\hang|xxx1| 241 |k[1]| |x[k]|. This command is undefined in
general; it functions as a $(k+2)$-byte |nop| unless special \.{GF}-reading
programs are being used. \MF\ generates \\{xxx} commands when encountering
a \&{special} string; this occurs in the \.{GF} file only between
characters, after the preamble, and before the postamble. However, \\{xxx}
commands can appear anywhere. It is recommended that |x| be a string
having the form of a keyword followed by possible parameters relevant to
that keyword.

\yskip\hang|@!xxx2| 242 |k[2]| |x[k]|. Like |xxx1|, but |0≤k<65536|.

\yskip\hang|xxx3| 243 |k[3]| |x[k]|. Like |xxx1|, but |0≤k<@t$2↑{24}$@>|.
\MF\ uses this when sending a \&{special} string whose length exceeds~255.

\yskip\hang|@!xxx4| 244 |k[4]| |x[k]|. Like |xxx1|, but |k| can be
ridiculously large; |k| mustn't be negative.

\yskip\hang|yyy| 245 |n[4]|. This command is undefined in general;
it functions as a 5-byte |nop| unless special \.{GF}-reading programs
are being used. \MF\ puts scaled numbers into |yyy|'s, as a
result of \&{numspecial} commands; the intent is to provide numeric
parameters to \\{xxx} commands that immediately precede.

\yskip\hang|char_loc| 246 |c[1]| |v[4]| |w[4]| |p[4]|.
This command will appear only in the postamble, which will be explained shortly.

\yskip\hang|pre| 247 |i[1]| |k[1]| |x[k]|.
Beginning of the preamble; this must come at the very beginning of the
file. Parameter |i| is an identifying number for \.{GF} format, currently
129. The other information is merely commentary; it is not given
special interpretation like \\{xxx} commands are. (Note that \\{xxx}
commands may immediately follow the preamble, before the first |boc|.)

\yskip\hang|post| 248. Beginning of the postamble, see below.

\yskip\hang|post_post| 249. Ending of the postamble, see below.

\yskip\noindent Commands 250--255 are undefined at the present time.

@d gf_id_byte=129 {identifies the kind of \.{GF} files described here}

@ Here are the opcodes \.{GFDOVER} actually refers to.

@d paint_0=0 {beginning of the \\{paint} commands}
@d paint1=64 {move right a given number of columns, then
	black${}\swap{}$white}
@d boc=67 {beginning of a character}
@d eoc=68 {end of a character}
@d skip1=69 {skip over blank rows}
@d new_row=72 {move down one row and adjust |z|}
@d right_z_0=156 {base of shorthand |new_row| commands}
@d right_z_1=157 {next shorthand |new_row| command}
@d right_z_83=239 {last shorthand |new_row| command}
@d left_z_83=73 {first shorthand |new_row| command}
@d nop=240 {no operation}
@d xxx1=241 {for \&{special} strings}
@d yyy=245 {for \&{numspecial} numbers}
@d char_loc=246 {character locators in the postamble}
@d pre=247 {preamble}
@d post=248 {postamble beginning}
@d post_post=249 {postamble ending}
@d undefined_commands==250,251,252,253,254,255

@ The last character in a \.{GF} file is followed by `|post|'; this command
introduces the postamble, which summarizes important facts that \MF\ has
accumulated. The postamble has the form
$$\vbox{\halign{\hbox{#\hfil}\cr
	|post| |p[4]| |@!ds[4]| |@!cs[4]| |@!hppp[4]| |@!vppp[4]|
	 |@!min_x[4]| |@!max_x[4]| |@!min_y[4]| |@!max_y[4]|\cr
	$\langle\,$character locators$\,\rangle$\cr
	|post_post| |q[4]| |i[1]| 223's$[{\G}4]$\cr}}$$
Here |p| is a pointer to the byte following the final |eoc| in the file
(or to the byte following the preamble, if there are no characters);
it can be used to locate the beginning of \\{xxx} commands
that might have preceded the postamble. The |ds| and |cs| parameters
give the design size and check sum, respectively, which are exactly the
values put into the header of the \.{TFM} file that \MF\ produces (or
would produce) on this run. Parameters |hppp| and |vppp| are the ratios of
pixels per point, horizontally and vertically, expressed as |scaled| integers
(i.e., multiplied by $2↑{16}$); they can be used to correlate the font
with specific device resolutions, magnifications, and ``at sizes.''  Then
come |min_x|, |max_x|, |min_y|, and |max_y|, which bound the values that |x|
and~|y| assume in all of the characters of this \.{GF} file.

@ Character locators are introduced by |char_loc| commands,
which contain a character residue~|c|, a character device width~|v|,
a character width~|w|, and a pointer~|p|
to the beginning of that character. (If two or more characters have the
same code~|c| modulo 256, only the last will be indicated; the others can be
located by following backpointers. Characters whose codes differ by a
multiple of 256 are assumed to share the same font metric information,
hence the \.{TFM} file contains only residues of character codes modulo~256.
This convention is intended for oriental languages, when there are many
character shapes but few distinct widths.)
@↑oriental characters@>@↑Chinese characters@>@↑Japanese characters@>

The character device width~|v| is the value of \MF's \&{chardw} parameter,
rounded to the nearest integer, i.e., the number of pixels that the font
designer wishes the character to occupy when it is typeset within a word.

The character width~|w| duplicates the information in the \.{TFM} file; it
is a |fix_word| value relative to the design size, and it should be
independent of magnification.

The backpointer |p| points to the character's |boc|, or to the first of
a sequence of consecutive |nop| or \\{xxx} or |yyy| commands that
immediately precede the |boc|, if such commands exist; such ``special''
commands essentially belong to the characters, while the special commands
after the final character belong to the postamble (i.e., to the font
as a whole). This convention about |p| applies also to the backpointers
in |boc| commands, even though it wasn't explained in the description
of~|boc|.

@ The last part of the postamble, following the |post_post| byte that
signifies the end of the character locators, contains |q|, a pointer to the
|post| command that started the postamble.  An identification byte, |i|,
comes next; this currently equals~129, as in the preamble.

The |i| byte is followed by four or more bytes that are all equal to
the decimal number 223 (i.e., @'337 in octal). \MF\ puts out four to seven of
these trailing bytes, until the total length of the file is a multiple of
four bytes, since this works out best on machines that pack four bytes per
word; but any number of 223's is allowed, as long as there are at least four
of them. In effect, 223 is a sort of signature that is added at the very end.
@↑Fuchs, David Raymond@>

This curious way to finish off a \.{GF} file makes it feasible for
\.{GF}-reading programs to find the postamble first, on most computers,
even though \MF\ wants to write the postamble last. Most operating
systems permit random access to individual words or bytes of a file, so
the \.{GF} reader can start at the end and skip backwards over the 223's
until finding the identification byte. Then it can back up four bytes, read
|q|, and move to byte |q| of the file. This byte should, of course,
contain the value 248 (|post|); now the postamble can be read, so the
\.{GF} reader can discover all the information needed for individual characters.

Unfortunately, however, standard \PASCAL\ does not include the ability to
@↑system dependencies@>
access a random position in a file, or even to determine the length of a file.
Almost all systems nowadays provide the necessary capabilities, so \.{GF}
format has been designed to work most efficiently with modern operating systems.
But if \.{GF} files have to be processed under the restrictions of standard
\PASCAL, one can simply read them from front to back. This will
be adequate for most applications. However, the postamble-first approach
would facilitate a program that merges two \.{GF} files, replacing data
from one that is overridden by corresponding data in the other.
@* Input and Output for binary files.
We have seen that a \.{GF} file is a sequence of 8-bit bytes. The bytes
appear physically in what is called a `|packed file of 0..255|'
in \PASCAL\ lingo.

Packing is system dependent, and many \PASCAL\ systems fail to implement
such files in a sensible way (at least, from the viewpoint of producing
good production software).  For example, some systems treat all
byte-oriented files as text, looking for end-of-line marks and such
things. Therefore some system-dependent code is often needed to deal with
binary files, even though most of the program in this section of
\.{GFDOVER} is written in standard \PASCAL.
@↑system dependencies@>

We shall stick to simple \PASCAL\ in this program, for reasons of clarity,
even if such simplicity is sometimes unrealistic.

@<Types...@>=
@!eight_bits=0..255; {unsigned one-byte quantity}
@!byte_file=packed file of eight_bits; {files that contain binary data}

@ The program deals with three binary file variables: |gf_file| is the
input file that we are translating into \.{OC} format, to be written
on |oc_file|, while we also accumulate width information that is written
on |wd_file|.

@<Glob...@>=
@!gf_file:byte_file; {the original source file}
@!oc_file:byte_file; {the desired OC output file}
@!wd_file:byte_file; {the desired WC output file}

@ To prepare the |gf_file| for input, we |reset| it.

@ Opening packed binary files:
@p procedure open_gf_file; {prepares to read packed bytes in |gf_file|}
begin reset(gf_file);
cur_loc←0;
end;

@ To prepare the |oc_file| for output, we |rewrite| it.

@p procedure open_oc_file; {prepares to write packed bytes in |oc_file|}
begin rewrite(oc_file);
oc_byte_no←0;
end;

@ To prepare the |wd_file| for output, we |rewrite| it.

@p procedure open_wd_file; {prepares to write packed bytes in |wd_file|}
begin rewrite(wd_file);
wd_byte_no←0;
end;

@ To prepare the |wd_file| for input, we |reset| it.

@p procedure reopen_wd_file; {prepares to read packed bytes in |wd_file|}
begin reset(wd_file);
wd_byte_no←0;
end;


@ It should be noted that |cur_loc| is a global variable that holds the
number of the byte about to be read next from |gf_file|.  Likewise,
|oc_byte_no| holds the number of the byte about to be written next into
|oc_file| while |wd_byte_no| holds the number of the byte about to be
written into |wd_file|.

@<Glob...@>=
@!cur_loc:integer; {where we are about to look, in |gf_file|}
@!oc_byte_no:integer; {where we are about to write, in |oc_file|}
@!wd_byte_no:integer; {where we are about to write, in |wd_file|}

@ We shall use a set of simple functions to read the next byte or
bytes from |gf_file|. There are seven possibilities, each of which is
treated as a separate function in order to minimize the overhead for
subroutine calls.
@↑system dependencies@>

@p function get_byte:integer; {returns the next byte, unsigned}
var b:eight_bits;
begin if eof(gf_file) then get_byte←0
else	begin read(gf_file,b); incr(cur_loc); get_byte←b;
	end;
end;
@#
function get_two_bytes:integer; {returns the next two bytes, unsigned}
var a,@!b:eight_bits;
begin read(gf_file,a); read(gf_file,b);
cur_loc←cur_loc+2;
get_two_bytes←a*256+b;
end;
@#
function get_three_bytes:integer; {returns the next three bytes, unsigned}
var a,@!b,@!c:eight_bits;
begin read(gf_file,a); read(gf_file,b); read(gf_file,c);
cur_loc←cur_loc+3;
get_three_bytes←(a*256+b)*256+c;
end;
@#
function signed_quad:integer; {returns the next four bytes, signed}
var a,@!b,@!c,@!d:eight_bits;
begin read(gf_file,a); read(gf_file,b); read(gf_file,c); read(gf_file,d);
cur_loc←cur_loc+4;
if a<128 then signed_quad←((a*256+b)*256+c)*256+d
else signed_quad←(((a-256)*256+b)*256+c)*256+d;
end;

@ Most info in the |oc_file| comes in words, but we have to write it
as bytes and halfwords occasionally.

@d oc_byte(#)==begin write(oc_file,#); incr(oc_byte_no); end

@p procedure oc_halfword(@!w:integer);
begin
if w<0 then w←w+@"10000;
oc_byte(w div @"100);
oc_byte(w mod @"100);
end;
@#
procedure oc_word(@!w:integer);
begin
if w>0 then oc_byte(w div @"1000000)
else begin
	w:=w+@"40000000;
	w:=w+@"40000000;
	oc_byte((w div @"1000000) + 128);
	end;
oc_byte((w div @"10000) mod @"100);
oc_byte((w div @"100) mod @"100);
oc_byte(w mod @"100);
end;

@ Simarlarly, most info in the |wd_file| comes in words, but we have to write it
as bytes and halfwords occasionally.

@d wd_byte(#)==begin write(wd_file,#); incr(wd_byte_no); end

@p procedure wd_halfword(@!w:integer);
begin
if w<0 then w←w+@"10000;
wd_byte(w div @"100);
wd_byte(w mod @"100);
end;
@#
procedure wd_word(@!w:integer);
begin
if w>0 then wd_byte(w div @"1000000)
else begin
	w:=w+@"40000000;
	w:=w+@"40000000;
	wd_byte((w div @"1000000) + 128);
	end;
wd_byte((w div @"10000) mod @"100);
wd_byte((w div @"100) mod @"100);
wd_byte(w mod @"100);
end;

@ Finally we come to the routines that are used for random access of the
|gf_file|. The driver program below needs two such routines: |gf_length| should
compute the total number of bytes in |gf_file|, possibly also
causing |eof(gf_file)| to be true; and |move_to_byte(n)|
should position |gf_file| so that the next |get_byte| will read byte |n|,
starting with |n=0| for the first byte in the file.
@↑system dependencies@>

Such routines are, of course, highly system dependent. They are implemented
here in terms of two assumed system routines called |set_pos| and |cur_pos|.
The call |set_pos(f,n)| moves to item |n| in file |f|, unless |n| is
negative or larger than the total number of items in |f|; in the latter
case, |set_pos(f,n)| moves to the end of file |f|.
The call |cur_pos(f)| gives the total number of items in |f|, if
|eof(f)| is true; we use |cur_pos| only in such a situation.

@p function gf_length:integer;
begin set_pos(gf_file,-1); gf_length←cur_pos(gf_file);
end;
@#
procedure move_to_byte(n:integer);
begin set_pos(gf_file,n); cur_loc←n;
end;
@* Reading the gf information.
The main work of \.{GFDOVER} is accomplished by the |do_char| routine.
This produces the output for an entire character, assuming that the |boc|
command for that character has already been processed. This procedure
works in two parts, the first of which is essentially an interpretive
routine that reads and acts on the \.{GF} commands by saving the preamble
and postamble information in tables and by writing the |paint| commands
into a condensed two-dimentional array, |paint_array[y,p_c]|, that can
then be scanned column-by-column reading bottom-to-top to produce the
required |oc| raster. This departs from the procedure recommended in
\.{GFTYPE} and it is responsible for a drastic reduction in the operating
time.  We also need to generate a simple array, |paint_val[y]|, that
reports the color (0 for white and 1 for black) of the first entry in eack
|y| column of the |paint_array|.

Rather than adjusting the size of the |paint_array| to meet the
requirements for each particular glyph, we assign an area large enough to
hold any reasonable sized glyph and arrange to clear only that portion of
the array that is actually used and do this just as the new input
information is being written into the array.

@ The definition of \.{GF} files refers to three registers,
$(x,y,z)$, which hold integer row and column numbers.

@<Types...@>=
@!x_coord=left_pixel..right_pixel;
@!y_coord=bot_pixel..top_pixel;
@!p_c_coord=0..max_p_c;

@ @<Glob...@>=
@!x,@!z: x_coord;
@!y:y_coord; {current state values}
@!min_z: x_coord;
@!paint_switch: pixel;
@!paint_array:array[min_y_allowed..max_y_allowed,0..max_p_c] of integer;
@!paint_val:array[min_y_allowed..max_y_allowed] of pixel;
@!p_c: p_c_coord; {used as second coordinate in |paint_array|}


@ In place of the recommended large array of pixels to hold the character image.
we use an array called |paint_array| of dimensions 
|max_y_allowed+1-min_y_allowed| and |max_p_c_allowed + 1|
to hold the yet to be interpreted paint commands 
and a |paint_val| of dimensions |max_y_allowed+1-min_y_allowed| to 
hold the current paint values (black or white) for the |y| row that is
next to be written out.

@d p_array==paint_array[y,p_c]
@d p_val==paint_val[y]
@d white==0 {could also be |false|}
@d black==1 {could also be |true|}
@d complement(#)==if #=black then #←white@+else #←black

@<Types...@>=
@!pixel=white..black; {could also be |boolean|}

@ Let's keep track of how many characters are in the font, and the
locations of where each one occured in the file.

@<Glob...@>=
@!total_chars:integer; {the total number of characters seen so far}
@!char_ptr: array[0..255] of integer; {correct character location pointer}
@!gf_prev_ptr: integer; {|char_ptr| for next character}
@!char_code: integer; {current character number}

@ @<Set init...@>=
for i←0 to max_glyph_no do char_ptr[i]←-1; 
      {mark characters as not being in the file}
total_chars←0;

@ Before we get into the details of |do_char|, it is convenient to
consider a simpler routine that computes the first parameter of each
opcode.

@d three_cases(#)==#,#+1,#+2
@d four_cases(#)==#,#+1,#+2,#+3
@d eight_cases(#)==four_cases(#),four_cases(#+4)
@d nine_cases(#)==eight_cases(#),#+8
@d sixteen_cases(#)==eight_cases(#),eight_cases(#+8)
@d nineteen_cases(#)==nine_cases(#),nine_cases(#+9),#+18
@d thirty_two_cases(#)==sixteen_cases(#),sixteen_cases(#+16)
@d sixty_four_cases(#)==thirty_two_cases(#),thirty_two_cases(#+32)
@d eighty_three_cases(#)==sixty_four_cases(#),nineteen_cases(#+64)

@p function first_par(o:eight_bits):integer;
begin case o of
sixty_four_cases(paint_0): first_par←o-paint_0;
paint1,skip1,char_loc,xxx1: first_par←get_byte;
paint1+1,skip1+1,xxx1+1: first_par←get_two_bytes;
paint1+2,skip1+2,xxx1+2: first_par←get_three_bytes;
new_row,xxx1+3,yyy: first_par←signed_quad;
nop,boc,eoc,pre,post,post_post,undefined_commands: first_par←0;
eighty_three_cases(left_z_83), right_z_0,
	eighty_three_cases(right_z_1): first_par←o-right_z_0;
end;
end;

@ Strictly speaking, the |do_char| procedure is really a function with
side effects, not a `\&{procedure}'\thinspace; it returns the value |false|
if \.{GFtype} should be aborted because of some unusual happening. The
subroutine is organized as a typical interpreter, with a multiway branch
on the command code.

@p function do_char:boolean;
label 9998,9999;
var o:eight_bits; {operation code of the current command}
@!p,@!q:integer; {parameters of the current command}
i,j:integer; {used as indices}
b:eight_bits; {holding byte for oc bits}
begin {we've already scanned the |boc|}
do_char←true;
while true do @<Translate the next command in the \.{GF} file;
		|goto 9999| if it was |eoc|;
		|goto 9998| if premature termination is needed@>;
9998: print_ln('!'); do_char←false;
9999:end;

@ @d show_label(#)==print(a:1,': ',#)
@d error(#)==begin show_label('! ',#); print_nl; end
@d start_op==a←cur_loc; o←get_byte; p←first_par(o);
	if eof(gf_file) then bad_gf('the file ended prematurely')
@.the file ended prematurely@>

@<Translate the next command...@>=
begin start_op;
@<Start translation of command |o| and |goto| the appropriate label to
	finish the job@>;
end

@* Translating the input commands.  This section will be largely concerned with
the reading of the input commands and the storing of this information in a
convenient form for future use.

@ The multiway switch in |first_par|, above, was organized by the length
of each command; the one in |do_char| is organized by the semantics.

@<Start translation...@>=
if o≤paint1+3 then @<Translate a sequence of |paint| commands,
	until reaching a non-|paint|@>;
if (new_row≤o) and (o≤right_z_83) then
	@<Translate a |new_row|, |right| or |left| command@>
else case o of
	three_cases(skip1): @<Translate a |skip| command@>;
	@t\4@>@<Cases for commands |nop|, |pre|, |post|, |post_post|, |boc|,
		and |eoc|@>@;
	four_cases(xxx1): @<Translate an |xxx| command@>;
	yyy: @<Translate a |yyy| command@>;
	othercases error('undefined command ',o:1,'!')
@.undefined command@>
	endcases

@ @<Cases for commands |nop|...@>=
nop: do_nothing;
pre: begin error('preamble command within a character!'); goto 9998;
	end;
@.preamble command within a page@>
post,post_post: begin error('postamble command within a character!');
@.postamble command within a page@>
	goto 9998;
	end;
boc: begin error('boc occurred before eoc!'); goto 9998;
@.boc occurred before eoc@>
	end;
eoc: begin
{|	print_nl;|}
	goto 9999;
	end;

@ @<Translate an |xxx| command@>=
begin  bad_char←false; n←16;
if p<0 then error('string of negative length!');
@.string of negative length@>
while p>0 do
	begin q←get_byte;
	if (q<" ")∨(q>"~") then bad_char←true;
	decr(p);
	end;
if bad_char then error('non-ASCII character in xxx command!');
@.non-ASCII character...@>
end

@ @<Glob...@>=
@!bad_char:boolean; {has a non-ASCII character code appeared in this \\{xxx}?}
@!n_r_flag:boolean; {has a |newrow| command just been executed?}

@ @<Translate a |yyy| command@>=
begin 
end

@ The bulk of a \.{GF} file generally consists of |paint| commands,
so we collect them together and store the extracted information in
the appropiate locations in the |paint_array|.

@<Translate a sequence of |paint| commands...@>=
begin
n_r_flag←false;
repeat @<Store it away@>;
start_op;
until o>paint1+3;
end

@ @<Store it away@>=
p_array←p;
incr(p_c);
p_array←0;
if p>0 then
	begin if y>max_y_observed then max_y_observed←y;
	if y<min_y_observed then min_y_observed←y;
	l←x; r←x+p-1;
	if r>max_x_observed then max_x_observed←r;
	if l<min_x_observed then min_x_observed←l;
	x←r+1;
	end;

@ @<Translate a |new_row|, |right| or |left| command@>=
begin
n_r_flag←true;
decr(y); z←z+p; x←z;
if z<min_z then min_z←z;
p_c←0; 
if z>0 then 
  begin
  p_val←white; 
  p_array←z;
  incr(p_c);
  p_array←0; {to clear the next |p_c| location}
  end else p_val←black;
end

@ @<Translate a |skip| command@>=
begin
p←p+1;
if n_r_flag=true then
  begin
  paint_val[y-p]←p_val;
  paint_array[y-p,0]←paint_array[y,0];
  paint_array[y-p,1]←paint_array[y,1];
  incr(y);
  end;
while p>0 do
  begin
  decr(y);
  p_val←white; paint_array[y,0]←0;
  decr(p);
  end;
decr(y);
end


@ We will have to make some calculations in floating point and convert the
results to integers.

@p function phys_size(i:integer):integer;
var r: real;
begin
{|r←i*magnification*2540/ppi;|}
r←i*magnification*2540/(ppi*16*unity);
phys_size←round(r);
end;

@ Still another procedure will soon be
needed to move the saved material from |wd_file| to the |oc_file|.

@p procedure move_rasters;
var b:eight_bits;
begin
reopen_wd_file;
b←0;
while not eof(wd_file) do
  begin
  read(wd_file,b); oc_byte(b); 
  end;
close(wd_file);
open_wd_file;  {rewrite in preparation for |wd| info}
end;


@ We may have occasion to tabulate the |p_array| information for debugging.
  
@p procedure tabulate;
var y: integer;
begin
print_ln('Tabulated results');
y←max_y_observed;
while y≥min_y_observed do  
  begin
  p_c←0;
  print_nl; print(y:3); 
  if p_val=0 then print('w':3) else print('b':3);
  while p_array>0 do
    begin
    print(p_array:3);

    incr(p_c);
    end;
  decr(y);
  end;
print_nl; print('End of tabulated results');
p_c←0;
end;
@* Processing and writing out the raster information.
As noted earlier, we will write the |oc| raster information into the
|wd_file| initially so the routines will refer to thd |wd_file| but it is
well to remember that it is actually |oc_file| information that is being
put away for safe keeping.

@ Before storing the raster information we will want to remove any existing
all-white columns at the left of the glyph.

@<Remove blank columns at the left@>=
min_y←min_y_stated; max_y←max_y_stated;
if min_z>0 then
  begin
  min_x←min_x_stated+min_z;
  y←min_y; p_c←0;
  while y<=max_y do
    begin
    if p_array≠0 then  {consider only non-blank rows}
      begin
      p_array←p_array-min_z;
      if p_array=0 then
        begin
        p_val←black;
        p_array←paint_array[y,1];
        p_c←1;
        while p_array≠0 do
          begin
	  p_array←paint_array[y,p_c+1];
	  incr(p_c);
	  end;
        p_c←0;
        end;
      end;
    incr(y);
    end;
  end;

@ We will also want to correct the value of |max_x| to define the actual
bounding box for the glyph as required by the |oc| format.

@<Establish new value of |max_x|@>=
max_x←min_x; y←max_y;
while y≥min_y do
  begin
  c←min_x; p_c←0;
  while p_array>0 do 
    begin
    c←c+p_array;
    incr(p_c);
    end;
  if c>max_x then max_x←c;
  decr(y);
  end;

@ We will not normally expect to encounter |skip| instructions between a
|boc| command and the first |paint| command or between the last |paint|
command and an |eoc| command, but should they occur, we will want to
ignore the blank rows that they produce in defining the bounding box as
used for the |oc| formulation.

@<Remove blank rows from top and bottom@>=
y←max_y; p_c←0;
while (p_array=0) and (y>min_y) do
  begin
  decr(y); max_y←y; {remove blank rows at the top}
  end;
y←min_y;
while (p_array=0) and (y<max_y) do
  begin
  incr(y); min_y←y; {remove blank rows at the bottom}
  end;

@ By this time we will have accumulated some information needed for
the |oc| preamble.

@<Save data for the |oc| file@>=
glyph_cols[char_code]←max_x+1-min_x; 
glyph_rows[char_code]←max_y+1-min_y; 
min_x_array[char_code]←min_x;
min_y_array[char_code]←min_y;

@ When edges are encountered while writing out the raster information, we
will find it convenient to call the following procedure in order to
complement the appropriate value of |p_val| and to move
the entries in |paint_array| so as to remove the exhausted paint entry,
	
@p procedure fix_val;
    begin
    complement(p_val);
    while p_array>0 do
      begin
      p_array←paint_array[y,p_c+1];
      incr(p_c);
      end;
    p_c←0;
    end;

@ We define the earliest raster position in the |oc| file to be '3000 (in
16-bit words) rounded up to the nearest multiple of 2*pagesizes (for
WAITS' sake).  @!@↑system dependencies@>

@<Constants...@>=
@! char_seg_file_pos=1536; {halfword where raster information is to start}

@ The following routine writes out the intended
|oc| raster, initially on the |wd_file|, while
observing the file position restriction just noted in recording the
|glyph_ptr| value.

@<Write the |oc| raster@>=
if glyph_ptr[char_code]≠-1 then error('Duplicate glyph');
glyph_ptr[char_code]←wd_byte_no div 2+char_seg_file_pos;
x←min_x; y←min_y; p_c←0;
while y≤max_y do
  begin
  b←p_val;
  if p_array>1 then decr(p_array) else
     if p_array=1 then fix_val;
  incr(y); i←2;
  if y<(max_y-6) then @<Get full byte@>
    else @<Get mixed byte@>;
  wd_byte(b);
  end;
if (wd_byte_no mod 2) ≠0 then wd_byte(0);

@ @<Get full byte@>=
  begin
  while i≤8 do
    begin
    b←b*2+p_val;
    if p_array>1 then decr(p_array) else
     if p_array=1 then fix_val;
    incr(y); incr(i);
    end;
  if (y>max_y) and (x<max_x) then 
    begin incr(x); y←min_y;
    end;
  end

@ @<Get mixed byte@>=
  begin
  while y≤max_y do
    begin
    b←b*2+p_val;
    if p_array>1 then decr(p_array) else
       if p_array=1 then fix_val;
    incr(y); incr(i);
    end;
  if x<max_x then
    begin
    y←min_y; incr(x);
    while i≤8 do
      begin
      b←b*2+p_val;
      if p_array>1 then decr(p_array) else
         if p_array=1 then fix_val;
      incr(y); incr(i);
      end;
    end
    else
    begin
    while i≤8 do
      begin
      b←b*2; incr(i);
      end;
    end;
  end
  
@* Reading the postamble.
Now imagine that we are reading the \.{GF} file and positioned just
after the |post| command. That, in fact, is the situation,
when the following part of \.{GFDOVER} is called upon to read, translate,
and check the rest of the postamble.

@p procedure read_postamble;
var k:integer; {loop index}
@!p,@!q,@!m,@!c:integer; {general purpose registers}
begin post_loc←cur_loc-1;
@.Postamble starts at byte n@>
p←signed_quad;
design_size←signed_quad; check_sum←signed_quad;@/
print('design size = ',design_size:1,' (');
print_scaled(design_size div 16);
print_ln(')');
font_face_byte←(design_size div 16) div unity;
font_face_byte←254-2*font_face_byte;
{|print_ln('check sum = ',check_sum:1);@/|}
hppp←signed_quad; vppp←signed_quad;@/
{|print('hppp = ',hppp:1,' ('); print_scaled(hppp); print_ln(')');|}
{|print('vppp = ',vppp:1,' ('); print_scaled(vppp); print_ln(')');|}
magnification←hppp/(65536.0*resolution/72.27);
oc_mag←round(1000*magnification);
{|print_ln('mag = ',oc_mag:1);|}
min_x←signed_quad; max_x←signed_quad;
min_y←signed_quad; max_y←signed_quad;@/
{|print_ln('min x = ',min_x:1,', max x = ',max_x:1);@/|}
{|print_ln('min y = ',min_y:1,', max y = ',max_y:1);@/|}
@<Process the character locations in the postamble@>;
@<Make sure that the end of the file is well-formed@>;
end;

@ Here is the main information we glean from the postamble together with
some auxiliary parameters.

@<Glob...@>=
@!design_size: integer;
@!hppp, @!vppp: integer;
@!check_sum: integer;
@!post_loc: integer;
@!magnification: real;
@!tfm_width: array [0..max_glyph_no] of integer;
@!device_width: array [0..max_glyph_no] of integer;
@!min_x, @!max_x, @!min_y, @!max_y: integer; {bounds of the current subarray}
@!min_x_stated, @!max_x_stated, @!min_y_stated, @!max_y_stated: integer;
	{bounds stated in the \.{GF} file}
@!min_x_observed,@!max_x_observed,@!min_y_observed,@!max_y_observed: integer;
	{bounds actually observed when painting}
@!min_x_overall, @!max_x_overall, @!min_y_overall, @!max_y_overall: integer;
	{bounds observed in the entire file so far}

@ When we get to the present code, the |post_post| command has
just been read.

@<Make sure that the end of the file is well-formed@>=
if k≠post_post then
	error('should be postpost!');
@.should be postpost@>
q←signed_quad;
if q≠post_loc then
	error('postamble pointer should be ',post_loc:1,' not ',q:1);
@.postamble pointer should be...@>
m←get_byte;
if m≠gf_id_byte then error('identification byte should be ',gf_id_byte:1);
@.identification byte should be n@>
k←cur_loc; m←223;
while (m=223)∧ not eof(gf_file) do m←get_byte;
if not eof(gf_file) then bad_gf('signature in byte ',cur_loc-1:1,
@.signature...should be...@>
		' should be 223')
else if cur_loc<k+4 then
	error('not enough signature bytes at end of file');
@.not enough signature bytes...@>

@ @<Process the character locations...@>=
repeat k←get_byte;
if k=char_loc then begin
	c←first_par(k);
	if c>max_glyph_no then abort('Character number too large');
	device_width[c]←signed_quad;
	tfm_width[c]←signed_quad;
	if tfm_width[c]<tfm_min then tfm_min←tfm_width[c];
	if tfm_width[c]>tfm_max then tfm_max←tfm_width[c];
	p←signed_quad;
	k←nop;
	end;
until k≠nop;

@ This routines is brought into play in order to read the postamble first.

@p procedure find_postamble;
var q,@!k: integer;
begin
post_loc←gf_length-4;
repeat if post_loc=0 then bad_gf('all 223s');
@.all 223s@>
move_to_byte(post_loc); k←get_byte; decr(post_loc);
until k≠223;
if k≠gf_id_byte then bad_gf('ID byte is ',k:1);
@.ID byte is wrong@>
move_to_byte(post_loc-3); q←signed_quad;
if (q<0)∨(q>post_loc-3) then bad_gf('post pointer ',q:1,' at byte ',post_loc-3:1);
@.post pointer is wrong@>
move_to_byte(q); k←get_byte;
if k≠post then bad_gf('byte ',q:1,' is not post');
@.byte n is not post@>
end;

@* OC File Format.
An \.{OC} file is an expanded raster description of a single font at a
particular resolution and contains only a portion of the information
that is contained in a \.{GF} file.  \.{OC} files are used by the Dover.
All words in of \.{OC} files are in 32-bit format, with the four lower
bits zero on 36-bit machines.

By convention, \.{OC} files are for 384 pixels per inch. \.{GFDOVER} will
report the magnification over the design point size that will occur if the
\.{OC} file is used on a 384 pixel per inch output device. Fonts
specifically designed for the Dover will report a magnification of 1000.

Data segments of type OrbitChars have an internal structure that is a
minature version of the structure of the complete dictionary file.  The
file begins with some general infomation about the font in general.  Then
there is a table that specifies the dimensions and widths of each
character in the font. Next there is a table of file pointers that give,
for each character code, the location of the corresponding raster block.
And finally, there are the raster blocks themselves.


The raster information is contained in a sequence of binary words that
record white pixels as zeros and black pixels as ones. Furthermore, this
raster information is written in a rotated form, as compared with the
convention for \.{PXL} files, reporting the pixels as read from the bottom
left corner of the glyph, reading up the leftmost column, with this being
followed imediately by the next column, again from bottom to top, without
any unused bit locations between columns. The final half word is, however
padded out with zeros.

Since the details of the header information for the \.{.OC} file cannot be
known until most of the work has been done toward creating the raster
information itself, the \.{OC} format arranges for the raster information
to start at byte '3000.  Originally the \.{OC} portion of \.{MF} was
designed to write zeros in the first '3000 bytes, then to procede to write
the raster information, one glyph at a time, and save the necessary header
information in global arrays, and only after the last glyph has been
processed, to then write out the header.  While this routine is easy to
follow in programs written in SAIL, it is difficult and indeed virtually
impossible with the simplified form of \.{PASCAL} as used in this program.

We therefore adopt an easier course, that of saving the \.{OC} raster information,
initially in the \.{WD} file, then of writing the \.{OC} header
information into the \.{OC} file as it is being generated. We then pad
this out, as required, and only then copy the raster
information from the \.{WD} file into the \.{OC} file. The necessary
\.{WD} information will have been kept in core until after this transfer
and the \.{WD} file will be |rewrite| opened and written in its final
form.


Returning to a consideration of the \.{OC} file,
the header consists of a block of 24 half-words that are characteristic of
the font in general followed by a character width table and finally by the
character-segment pointers.

The \.{OC} format requires the different glyphs to be arranged in |char_code|
order, although there is no such requirement in \.{MF}.
There need not be a complete set of 128 glyphs in the font but the format was designed
on the assumption
that the set would be reasonably complete within a group from a
character number of |bc| through |ec|.  There will be a set of 8
half-words of width information for each character within this group (with
a standard notation for all missing glyphs).

There will be a similar set of |ec| $-$ |bc| $+$ 1 pointers, each
occupying two half-words, for the raster information for each character
(with pointers of $-1$ for missing characters).

The initial 24 half-words of the header will contain:
\smallskip\hang\noindent
0. A header for the family-name IX.
\smallskip\hang\noindent
1. The font name code.
\smallskip\hang\noindent
2..11.. A 20-character font identifier string.
\smallskip\hang\noindent
12. Header for orbit-chars IX.
\smallskip\hang\noindent
13. Name code again in left byte and logical size encoded as face byte.
\smallskip\hang\noindent
14. |bc| in left byte and |ec| in right byte.
\smallskip\hang\noindent
15. Physical size in micas (real).
\smallskip\hang\noindent
16. Rotation in minutes of arc.
\smallskip\hang\noindent
17..18. Starting file position of font segment.
\smallskip\hang\noindent
19..20. Font segment length.
\smallskip\hang\noindent
21. X resolution in units of pixels/(10 inchs) (real)
\smallskip\hang\noindent
22. Y resolution in units of pixels/(10 inches) (real).
\smallskip\hang\noindent
23. EndIX.
\smallskip

The 8 words of width information for each |ec|$-$|bc|$+1$ entry will contain:
\smallskip\hang\noindent
0,1. X-width$*$xresolution$*(2↑(16))$.
\smallskip\hang\noindent
2,3. Y-width$*$yresolution$*(2↑(16))$.
\smallskip\hang\noindent
4. Bounding box x-offset.
\smallskip\hang\noindent
5. Bounding box y-offset.
\smallskip\hang\noindent
6. Bounding box x-width in scan lines.
\smallskip\hang\noindent
7. Bounding box y-height in bits.
\smallskip

Finally the raster information for each glyph will occupy a varying amount
of space up to a limit of 
(((|right_pixel|-|left_pixel|)*(|top_pixel|-|bot_pixel|)+15)div 16 half-words,
although most glyphs will not occupy this much space.

@ @<Glob...@>=
@!glyph_ptr: array [0..max_glyph_no] of integer; {called charsegptr in MFDOVR}
@!glyph_cols: array [0..max_glyph_no] of integer; {BBdxArray in MFDOVR}
@!glyph_rows: array [0..max_glyph_no] of integer; {BBdyArray in MFDOVR}
@!min_x_array: array [0..max_glyph_no] of integer; {BBoxArray in MFDOVR}
@!min_y_array: array [0..max_glyph_no] of integer; {BBoyArray in MFDOVR}
@!x_char_width: array [0..max_glyph_no] of integer;
@!cols_offset: array [0..max_glyph_no] of integer; 
@!rows_offset: array [0..max_glyph_no] of integer; 
@!bc, @!ec, @!nc: integer;
@!oc_dir_ptr:integer;
@!oc_mag: integer;
@!seg_start: integer;
@!seg_end: integer;
@!font_face_byte: integer;
@!rel_ptr_base: integer;
@!pix_res: integer;
@!fixed_x:boolean; {true for a fixed-character-width font}

@!cols_max,rows_max: integer; {x and y dimensions of font bounding box}
@!tfm_min,tfm_max:integer; {|tfm_width| range for font bounding box}

@ @<Set init...@>=
for i←0 to max_glyph_no do 
begin 
glyph_cols[i]←0;
glyph_rows[i]←0;
cols_offset[i]←0;
rows_offset[i]←0;
glyph_ptr[i]←-1; {marks nonexistant character}
end;
bc←max_glyph_no+1; ec←-1;

tfm_min←1000; tfm_max←0;
cols_max←0; rows_max←0;
min_x_overall←max_int;  min_y_overall←max_int;  {any large number will do}
max_x_overall←0;  max_y_overall←0;

@ There is a certain amount of initial information that must be written on
the |oc_file|.

@<Write the |oc| initial information@>=
begin
bc←0; while (glyph_ptr[bc]=-1) and (bc<max_glyph_no) do incr(bc);
ec←max_glyph_no;
while (glyph_ptr[ec]=-1) and (ec>0) do decr(ec);
if bc>ec then error('No characters in this font!');
nc←ec+1-bc;
print_nl; print('bc = ',bc:1); print(' ec = ',ec:1);
seg_start←char_seg_file_pos-(8+2)*nc;
seg_end←char_seg_file_pos+(wd_byte_no div 2);
if (font_face_byte<0) or (font_face_byte>256)  then error('Fontface out of bnds');
oc_halfword(4108); {header for family-name IX}
oc_halfword(0); {name code}
oc_word(0); {|oc_string(fontidentifier,20);| goes in here, replacing 5 words}
oc_word(0);
oc_word(0);
oc_word(0);
oc_word(0);
oc_halfword(20491); {header for orbit-chars IX}
oc_byte(0); {name code again}
oc_byte(bc); {charcode for the first glyph}
oc_byte(ec); {charcode for the last glyph}
oc_byte(font_face_byte); {logical size encoded as font face byte}
oc_halfword(phys_size(design_size)); {physical size in micas}
oc_halfword(0); {rotation in minutes of arc}
oc_word(char_seg_file_pos); {starting file pos of font segment in halfwords}
oc_word(wd_byte_no div 2); {font segment length in half words}
pix_res←round(3840/magnification+0.5);
oc_halfword(pix_res);
oc_halfword(pix_res);
oc_halfword(1); {endIX}
if oc_byte_no≠48 then error('This cannot happen: header error');
{|print(oc_byte_no:5);|}
while oc_byte_no<2*seg_start do oc_halfword(0); 
c←bc;
while c≤ec do 
  begin
  if glyph_ptr[c]≠-1 then
    begin
    oc_word(round(xresolution*tfm_width[c])); {*** this is probably not correct ***}
    oc_word(0);  {assuming not vectorwidths}
    oc_halfword(min_x_array[c]);
    oc_halfword(min_y_array[c]);
    oc_halfword(glyph_cols[c]);
    oc_halfword(glyph_rows[c]);
    end else
    begin
    i←1;
    while i≤7 do
      begin
      oc_halfword(0);
      incr(i);
      end;
    oc_halfword(-1);
    end;
    incr(c);
  end;
rel_ptr_base←char_seg_file_pos-2*nc;
if oc_byte_no≠2*rel_ptr_base then error('rel ptr base error');
c←bc;
while c≤ec do
  begin
  if glyph_ptr[c]≠-1 then oc_word(glyph_ptr[c]-rel_ptr_base)
  else oc_word(-1);
  incr(c);
  end;
close(wd_file);
end

@ Certain parameters are computed as reals and then stored as integers.
It is possible for these parameters to exceed the bounds set by the .wd
format.

@p procedure wd_real(r:real);
var int:integer;
begin
int←round(r*1000/design_size);
if abs(int)>32766 then error('value exceeds bounds of .wd format!');
wd_halfword(int);
end;

@ After copying the |oc| header information from the \.{WD} file into the \.{WD}
file and resetting the \.{WD} file we can then write out the following:

@<Write |wd| information@>=
wd_halfword(4108); {header for family-name IX}
wd_halfword(0); {name code}
wd_word(0); {|wd_string(fontidentifier,20);| goes in here, replacing 5 words}
wd_word(0);
wd_word(0);
wd_word(0);
wd_word(0);
wd_halfword(20491); {header for orbit-chars IX}
wd_byte(0); {name code again}
wd_byte(font_face_byte); {logical size encoded as font face byte}
wd_byte(bc); {charcode for the first glyph}
wd_byte(ec); {charcode for the last glyph}
wd_halfword(0); {physical size field, 0 means scalable};
wd_halfword(0); {rotation in minutes of arc}
wd_word(22); {starting file pos of font segment in halfwords}
if fixed_x then wd_word(7) else wd_word(nc+6); {data segment length in half words}
wd_halfword(1); {endIX}
if wd_byte_no≠44 then error('This cannot happen: header error');
{|print(wd_byte_no:5);|}
wd_real(min_x_overall/xresolution); {x offset of font bounding box}
wd_real(min_y_overall/yresolution); {y offset of font bounding box}
wd_real(cols_max/xresolution); {x dimension of font bounding box}
wd_real(rows_max/yresolution); {y dimension of font bounding box}
if tfm_min=tfm_max then fixed_x←true else fixed_x←false; {fixed-y is true always}
if fixed_x then wd_byte(192) else wd_byte(64); {fixed flags}
wd_byte(0); {flags are actually stored in a half word, this fills it out}
if fixed_x then wd_halfword(tfm_max)
  else
  begin
  c←bc;
  while c≤ec do
    begin
    if glyph_ptr[c]=-1 then 
      begin wd_byte(128);wd_byte(0);
      end
    else wd_halfword(tfm_width[c]);  { *** this needs verification *** }
    incr(c);
    end;
  end;
wd_halfword(0);
if wd_byte_no≠56+2*nc then 
  begin print_nl; print(wd_byte_no); print(' instead of ',56+2*nc:1);
  end;
if (wd_byte_no mod 4)≠0 then wd_halfword(0);


@* The main program.
Now we are ready to put it all together. This is where \.{GFDOVER} starts,
and where it ends.

@p begin initialize; {get all variables initialized}
open_gf_file;
find_postamble; read_postamble;
@<Process the preamble@>;
open_oc_file;
open_wd_file;
@<Translate all the characters@>;
@<Write the |oc| initial information@>;
move_rasters;
print_nl; print('Font had ',total_chars:1,' character');
if total_chars≠1 then print('s'); print(' altogether');
@<Write |wd| information@>;
final_end:end.

@ The main program needs a few global variables in order to do its work.

@<Glob...@>=
@!a:integer; {byte number of the current command}
@!b,i:integer; {used in accumulating output byte information}
@!c,@!l,@!m,@!n,@!o,@!p,@!q,@!r:integer; {general purpose registers}

@ \.{GFDOVER} looks at the preamble in order to do error checking, and to
display the introductory comment.

@<Process the preamble@>=
open_gf_file;
o←get_byte; {fetch the first byte}
if o≠pre then bad_gf('First byte isn''t start of preamble!');
@.First byte isn't...@>
o←get_byte; {fetch the identification byte}
if o≠gf_id_byte then
	error('identification byte should be ',gf_id_byte:1,
	' not ',o:1,'!');
@.identification byte should be n@>
o←get_byte; {fetch the length of the introductory comment}
print('''');
while o>0 do
	begin decr(o); print(xchr[get_byte]);
	end;
print_ln('''');

@ @<Translate all...@>=
repeat gf_prev_ptr←cur_loc;
	@<Pass |nop|, |xxx| and |yyy| commands@>;
	if o≠post then
		begin if o≠boc then
			bad_gf('byte ',cur_loc-1:1,' is not boc (',o:1,')');
{|		print(cur_loc:1);|}
		print(' [');
		@<Pass a |boc| command@>;
		if not do_char then bad_gf('char ended unexpectedly');
		@<Pass an |eoc| command@>;
		@<Remove blank columns at the left@>;
		@<Establish new value of |max_x|@>;
		@<Remove blank rows from top and bottom@>;
{|	        tabulate;|}
		@<Save data for the |oc| file@>;
                @<Write the |oc| raster@>;
		print(']');
		end;
until o=post;


@ @<Pass |nop|, |xxx| and |yyy| commands@>=
repeat
	a←cur_loc;
	o←get_byte; p←first_par(o);
	if eof(gf_file) then bad_gf('the file ended prematurely');
@.the file ended prematurely@>
	if o=yyy then begin @<Translate a |yyy|...@>; o←nop; end
	else if (o≥xxx1) and (o≤xxx1+3) then begin
		@<Translate an |xxx|...@>; o←nop;
		end;
until o≠nop;

@ @<Pass a |boc|...@>=
a←cur_loc;
incr(total_chars);
char_code←signed_quad;
p←signed_quad;
c←char_code mod 256;
if c<0 then c←c+256;
print(c:1);
if char_code≠c then
	print(' in family ',(char_code-c) div 256 : 1);
min_x_stated←signed_quad; max_x_stated←signed_quad;
min_y_stated←signed_quad; max_y_stated←signed_quad;
z←signed_quad;
min_z←z;
min_x_observed←max_int; max_x_observed←-max_int;
min_y_observed←max_int; max_y_observed←-max_int;
if char_ptr[c]≠p then
	error('previous character pointer should be ',char_ptr[c]:1,
		', not ',p:1,'!');
char_ptr[c]←gf_prev_ptr;
y←max_y_stated;
x←z;
p_c←0;
p_val←white; p_array←z; incr(p_c); p_array←0;

@ @<Pass an |eoc|...@>=
if min_x_observed<min_x_overall then min_x_overall←min_x_observed;
if max_x_observed>max_x_overall then max_x_overall←max_x_observed;
if min_y_observed<min_y_overall then min_y_overall←min_y_observed;
if max_y_observed>max_y_overall then max_y_overall←max_y_observed;
@* System-dependent changes.
This section should be replaced, if necessary, by changes to the program
that are necessary to make \.{GFDOVER} work at a particular installation.
It is usually best to design your change file so that all changes to
previous sections preserve the section numbering; then everybody's version
will be consistent with the printed program. More extensive changes,
which introduce new sections, can be inserted here; then only the index
itself will get a new section number.
@↑system dependencies@>
@* Index.
Pointers to error messages appear here together with the section numbers
where each ident\-i\-fier is used.